{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  文档\n",
    "- 人脸识别api文档 https://ai.baidu.com/ai-doc/FACE/Lk37c1tpf\n",
    "- 百度驾驶行为分析API价格文档https://ai.baidu.com/ai-doc/BODY/mk3cpyhfe#2-%E6%8C%89%E8%B0%83%E7%94%A8%E9%87%8F%E8%AE%A1%E8%4%B9\n",
    "- 百度语音合成API技术文档https://ai.baidu.com/ai-doc/SPEECH/yk38y8h3j"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 驾驶行为分析"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.52d8c288a5c624af9cb3c95499fde94d.315360000.1926729755.282335-22869824', 'expires_in': 2592000, 'session_key': '9mzdCrclFDjMcChuPNRoTuTn5nBXHWuwpxXwccj9QhPz2Hn1aRwENBAY9w7xEN4hWC+InsmVWTYnHArsKRDm7KsKoIP5lg==', 'access_token': '24.1370946c683cbf44992f175810d6aa1e.2592000.1613961755.282335-22869824', 'scope': 'public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_idl_face_merge vis-faceverify_FACE_EFFECT vis-faceverify_face_feature_sdk wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin', 'session_secret': 'dcfcaa5c48506349b794a54b99e9d20e'}\n"
     ]
    }
   ],
   "source": [
    "# 代码来源自文档\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=LakbMzSMGELavcGZxKirr3kU&client_secret=z3HLq6UoBbCRBuMbGxNGlcP6rVaoDlnB'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "access_token: '24.1c13146ede07e493fec0a4008138a730.2592000.1613913364.282335-23578181'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'log_id': 1352808922796261376,\n",
       " 'person_num': 1,\n",
       " 'person_info': [{'location': {'score': 0.92749613523483,\n",
       "    'top': 56,\n",
       "    'left': 85,\n",
       "    'width': 269,\n",
       "    'height': 276},\n",
       "   'attributes': {'both_hands_leaving_wheel': {'score': 0.022068621590734,\n",
       "     'threshold': 0.75},\n",
       "    'eyes_closed': {'score': 0.00015267658181983, 'threshold': 0.55},\n",
       "    'no_face_mask': {'score': 0.99847811460495, 'threshold': 0.75},\n",
       "    'not_buckling_up': {'score': 0.29132068157196, 'threshold': 0.44},\n",
       "    'smoke': {'score': 0.00045323037193157, 'threshold': 0.48},\n",
       "    'cellphone': {'score': 0.0018496389966458, 'threshold': 0.69},\n",
       "    'not_facing_front': {'score': 0.0041032442823052, 'threshold': 0.5},\n",
       "    'yawning': {'score': 7.8874040809751e-05, 'threshold': 0.5},\n",
       "    'head_lowered': {'score': 0.0002012311572912, 'threshold': 0.55}}}],\n",
       " 'driver_num': 1}"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests,json\n",
    "import base64\n",
    "\n",
    "'''\n",
    "驾驶行为API\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior\"\n",
    "\n",
    "#图片需要经过64base编码\n",
    "p = open('D:\\样图.jpg','rb')\n",
    "img = base64.b64encode(p.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.1c13146ede07e493fec0a4008138a730.2592000.1613913364.282335-23578181'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "response.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 语音合成技术 （需要先导入百度SDK库）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "转化完成 保存在D：\\API\n"
     ]
    }
   ],
   "source": [
    "from aip import AipSpeech\n",
    "\n",
    "\"\"\" 你的 APPID AK SK \"\"\"\n",
    "APP_ID = '22976999'\n",
    "API_KEY = 'copaj4VBhgsEmjOGTukQp0tO'\n",
    "SECRET_KEY = '39xVsxIw0IrmLMNesB0COAZSjI6eDnz6'\n",
    "\n",
    "client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)\n",
    "\n",
    "result  = client.synthesis('请佩戴口罩。', 'zh', 1, {\n",
    "    'vol': 5,   # 更多参数查看pythonSDK文档\n",
    "})\n",
    "save_name = 'D:\\API' + '.mp3'\n",
    "# 识别正确返回语音二进制 错误则返回dict 参照下面错误码\n",
    "print(\"转化完成 保存在D：\\API\")\n",
    "if not isinstance(result, dict):\n",
    "    with open(save_name, 'wb')as f:\n",
    "        f.write(result)\n",
    "\n",
    "# 在本地生成一个mp3格式的语音文件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 人脸对比"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "图片识别相似度度为93.6747818%,是同一人\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "import json\n",
    "# 1，准备好申请的人脸识别api，API Key， Secret Key\n",
    "api1=\"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=LakbMzSMGELavcGZxKirr3kU&client_secret=z3HLq6UoBbCRBuMbGxNGlcP6rVaoDlnB\"\n",
    "# api2=\"https://aip.baidubce.com/rest/2.0/face/v3/match\"\n",
    "\n",
    "# 2,获取token值，拼接API\n",
    "def get_token():\n",
    "    response=requests.get(api1)\n",
    "    access_token=eval(response.text)['access_token']\n",
    "    api2=\"https://aip.baidubce.com/rest/2.0/face/v3/match\"+\"?access_token=\"+access_token\n",
    "    return api2\n",
    "\n",
    "api2 =\"https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=24.1c13146ede07e493fec0a4008138a730.2592000.1613913364.282335-23578181\"\n",
    "\n",
    "# 3,读取图片数据\n",
    "def read_img(img1,img2):\n",
    "    with open(img1,'rb') as f:\n",
    "        pic1=base64.b64encode(f.read())\n",
    "    with open(img2,'rb') as f:\n",
    "        pic2=base64.b64encode(f.read())\n",
    "    params=json.dumps([\n",
    "        {\"image\":str(pic1,\"utf-8\"),\"image_type\":'BASE64',\"face_type\":\"LIVE\"},\n",
    "        {\"image\":str(pic2,\"utf-8\"),\"image_type\":'BASE64',\"face_type\":\"IDCARD\"}\n",
    "    ])\n",
    "    return params\n",
    "\n",
    "# 4，发起请求拿到对比结果\n",
    "def analyse_img(file1,file2):\n",
    "    params=read_img(file1,file2)\n",
    "    api=get_token()\n",
    "    content=requests.post(api,params).text\n",
    "    # print(content)\n",
    "    score=eval(content)['result']['score']\n",
    "    if score>80:\n",
    "        print('图片识别相似度度为'+str(score)+'%,是同一人')\n",
    "    else:\n",
    "        print('图片识别相似度度为'+str(score)+'%,不是同一人')\n",
    "\n",
    "analyse_img(\"img1.jpg\",\"img2.jpg\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
